<?php
/**
 * CreateTime: 2022/9/21 14:49
 */

namespace App\Service\Approval\ApprovalContract;

use App\Consts\Approval\ApprovalSubmitTypeConsts;
use App\Consts\ContractConsts\NewContractApprovalStatus;
use App\Models\NewContract\ContractModel;
use App\Models\NewContract\FulfillmentModel;
use App\Models\NewContract\FulfillmentNodeModel;
use App\Service\Approval\DingTalkApprovalInterFace;
use App\Tools\Log\Log;
use Illuminate\Support\Facades\DB;

class ApprovalSealContract implements DingTalkApprovalInterFace
{

    public function approvalStart($processInstanceId, $sourceId, $processStatus)
    {
        // 修改合同审批状态为送签中
        (new ContractModel())->editContract($sourceId,[
            'contract_status' =>NewContractApprovalStatus::CONTRACT_APPROVAL_QSZ
        ]);
    }

    public function approvalAgreeEnd($processInstanceId, $sourceId, $processStatus)
    {
        DB::beginTransaction();
        try {
            $cm = new ContractModel();
            $fm = new FulfillmentModel();
            $fmn = new FulfillmentNodeModel();
            // 修改合同状态为已签署
            $cm->editContract($sourceId,[
                'contract_status' =>NewContractApprovalStatus::CONTRACT_APPROVAL_YQS
            ]);
            // 修改当前合同下的所有履约为代履行
            $fm->editFulfillmentDlyByContractId($sourceId);
            // 检查当前合同是否为附属合同
            $contractInfo = $cm->getContractInfo($sourceId,'contract_sub_type,parent_id');
            // 如果当前是附属合同则修改以前的履约已废弃 并且把汇总数据变为已废弃
            // 查出所有父级合同的履约条款废弃其所有的履约节点
            if(@$contractInfo['parent_id'] && $contractInfo['contract_sub_type'] == 1){
                $fmnIds = $fmn->getFulfillmentNodeListByContractId($sourceId,['fulfillment_node_id']);
                $fm->deleteAbandonFulfillmentByContractId($sourceId);
            }

            DB::commit();
        }catch (\Exception $exception){
            Log::e($exception);
            DB::rollBack();
        }
    }

    public function approvalRefuseEnd($processInstanceId, $sourceId, $processStatus)
    {
        // 修改合同状态为已退回
        // 修改合同审批状态为审批中
        (new ContractModel())->editContract($sourceId,[
            'contract_status' =>NewContractApprovalStatus::CONTRACT_APPROVAL_ZF
        ]);
    }
}